/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pig.juhe.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.juhe.admin.mapper.JuheChannelAttrMapper;
import com.pig4cloud.pig.juhe.admin.mapper.JuheChannelAttrValueMapper;
import com.pig4cloud.pig.juhe.admin.mapper.JuheChannelInfoMapper;
import com.pig4cloud.pig.juhe.admin.mapper.JuheGameInfoMapper;
import com.pig4cloud.pig.juhe.api.entity.JuheChannelAttr;
import com.pig4cloud.pig.juhe.api.entity.JuheChannelAttrValue;
import com.pig4cloud.pig.juhe.api.entity.JuheChannelInfo;
import com.pig4cloud.pig.juhe.api.entity.JuheGameChannel;
import com.pig4cloud.pig.juhe.admin.mapper.JuheGameChannelMapper;
import com.pig4cloud.pig.juhe.admin.service.JuheGameChannelService;
import com.pig4cloud.pig.juhe.api.entity.JuheGameInfo;
import com.pig4cloud.pig.juhe.api.request.AttrValueRequest;
import com.pig4cloud.pig.juhe.api.request.JuheGameChannelRequest;
import com.pig4cloud.pig.juhe.api.util.Constant;
import com.pig4cloud.pig.juhe.api.vo.JuheChannelAttrValueVo;
import com.pig4cloud.pig.juhe.api.vo.JuheGameChannelVo;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 聚合游戏渠道关系表
 *
 * @author yuwenfeng
 * @date 2021-09-02 13:56:17
 */
@Service
@AllArgsConstructor
public class JuheGameChannelServiceImpl extends ServiceImpl<JuheGameChannelMapper, JuheGameChannel> implements JuheGameChannelService {

	private final JuheChannelAttrValueMapper juheChannelAttrValueMapper;
	private final JuheChannelInfoMapper juheChannelInfoMapper;
	private final JuheGameInfoMapper juheGameInfoMapper;
	private final JuheChannelAttrMapper juheChannelAttrMapper;

	@Override
	public Page<JuheGameChannelVo> selectGameChannelVoPage(Page<JuheGameChannel> page, QueryWrapper<JuheGameChannel> query) {
		return baseMapper.selectGameChannelVoPage(page, query);
	}

	@Override
	public JuheGameChannelVo getGameChannelVoById(Long recordId) {
		JuheGameChannelVo vo = baseMapper.selectGameChannelVoById(recordId);
		if (null != vo) {
			List<JuheChannelAttrValueVo> attrValueList = new ArrayList<JuheChannelAttrValueVo>();
			//获取渠道属性配置
			List<JuheChannelAttr> attrList = juheChannelAttrMapper.selectList(new QueryWrapper<JuheChannelAttr>().eq("channel_id", vo.getChannelId()));
			if (CollectionUtils.isNotEmpty(attrList)) {
				JuheChannelAttrValueVo attrValueVo = null;
				for (JuheChannelAttr attr : attrList) {
					attrValueVo = JSONObject.parseObject(JSONObject.toJSONString(attr), JuheChannelAttrValueVo.class);
					JuheChannelAttrValue attrValue = juheChannelAttrValueMapper.selectOne(new QueryWrapper<JuheChannelAttrValue>().eq("channel_id", vo.getChannelId()).eq("game_id", vo.getGameId()).eq("attr_id", attr.getAttrId()).eq("del_flag", Constant.DEL_NO));
					if (null != attrValue) {
						attrValueVo.setAttrValue(attrValue.getAttrValue());
					}
					attrValueList.add(attrValueVo);
				}
				vo.setAttrValueList(attrValueList);
			}
		}
		return vo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R addGameChannel(JuheGameChannelRequest juheGameChannel) {
		if (null != juheGameChannel.getPrivacyOff() && 1 == juheGameChannel.getPrivacyOff()) {
			if (StringUtils.isBlank(juheGameChannel.getPrivacyUrl())) {
				return R.failed("隐私开关打开时，隐私地址不能为空");
			}
			if (StringUtils.isNotBlank(juheGameChannel.getPrivacyUrl())) {
				if (!Pattern.matches(Constant.URL_REGEXP, juheGameChannel.getPrivacyUrl())) {
					return R.failed("隐私地址内容不合法");
				}
			}
		}
		JuheChannelInfo channelInfo = juheChannelInfoMapper.selectById(juheGameChannel.getChannelId());
		if (null == channelInfo) {
			return R.failed("渠道不存在");
		}
		JuheGameInfo gameInfo = juheGameInfoMapper.selectById(juheGameChannel.getGameId());
		if (null == gameInfo) {
			return R.failed("游戏不存在");
		}
		long num = baseMapper.selectCount(new QueryWrapper<JuheGameChannel>().eq("channel_id", channelInfo.getChannelId()).eq("game_id", gameInfo.getGameId()).eq("del_flag", Constant.DEL_NO));
		if (num > 0) {
			return R.failed("该游戏渠道已存在");
		}
		JuheGameChannel info = JSON.parseObject(JSON.toJSONString(juheGameChannel), JuheGameChannel.class);
		if (CollectionUtils.isNotEmpty(juheGameChannel.getAttrValueList())) {
			//获取渠道属性配置
			List<JuheChannelAttr> attrList = juheChannelAttrMapper.selectList(new QueryWrapper<JuheChannelAttr>().eq("channel_id", channelInfo.getChannelId()));
			JuheChannelAttrValue attrValue = null;
			for (JuheChannelAttr sysAttr : attrList) {
				for (AttrValueRequest attr : juheGameChannel.getAttrValueList()) {
					if (sysAttr.getAttrKey().equals(attr.getAttrKey())) {
						if (1 == sysAttr.getAttrRequired() && StringUtils.isBlank(attr.getAttrValue())) {
							throw new BusinessException(1000, sysAttr.getAttrName() + "参数不能为空");
						}
						//判断是否有重复的key
						int attrValueNum = juheChannelAttrValueMapper.selectCount(new QueryWrapper<JuheChannelAttrValue>().eq("channel_id", info.getChannelId()).eq("game_id", info.getGameId()).eq("attr_id", sysAttr.getAttrId()).eq("del_flag", Constant.DEL_NO));
						if (attrValueNum > 0) {
							throw new BusinessException(1000, "该游戏渠道的属性KEY：" + sysAttr.getAttrName() + "已存在，无法添加");
						}
						//校验华为文件类型
						if (Constant.HUAWEI_JSON_KEY.equals(attr.getAttrKey())) {
							String extension = attr.getAttrValue().substring(attr.getAttrValue().lastIndexOf('.') + 1);
							if (!Constant.JSON.equalsIgnoreCase(extension)) {
								throw new BusinessException(1000, "文件不合法,必须为" + Constant.JSON + "文件");
							}
						}
						attrValue = new JuheChannelAttrValue();
						attrValue.setAttrId(sysAttr.getAttrId());
						attrValue.setAttrValue(attr.getAttrValue());
						attrValue.setChannelId(channelInfo.getChannelId());
						attrValue.setGameId(gameInfo.getGameId());
						juheChannelAttrValueMapper.insert(attrValue);
					}
				}
			}
		}
		int statusNum = baseMapper.insert(info);
		if (statusNum > 0) {
			return R.ok();
		} else {
			return R.failed("新增操作异常");
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R editGameChannel(JuheGameChannelRequest juheGameChannel) {
		if (null != juheGameChannel.getPrivacyOff() && 1 == juheGameChannel.getPrivacyOff()) {
			if (StringUtils.isBlank(juheGameChannel.getPrivacyUrl())) {
				return R.failed("隐私开关打开时，隐私地址不能为空");
			}
			if (StringUtils.isNotBlank(juheGameChannel.getPrivacyUrl())) {
				if (!Pattern.matches(Constant.URL_REGEXP, juheGameChannel.getPrivacyUrl())) {
					return R.failed("隐私地址内容不合法");
				}
			}
		}
		JuheGameChannel info = baseMapper.selectById(juheGameChannel.getRecordId());
		if (null == info) {
			return R.failed("游戏渠道不存在");
		}
		JuheChannelInfo channelInfo = juheChannelInfoMapper.selectById(juheGameChannel.getChannelId());
		if (null == channelInfo) {
			return R.failed("渠道不存在");
		}
		JuheGameInfo gameInfo = juheGameInfoMapper.selectById(juheGameChannel.getGameId());
		if (null == gameInfo) {
			return R.failed("游戏不存在");
		}
		List<JuheGameChannel> gameChannelList = baseMapper.selectList(new QueryWrapper<JuheGameChannel>().eq("channel_id", juheGameChannel.getChannelId()).eq("game_id", juheGameChannel.getGameId()).eq("del_flag", Constant.DEL_NO));
		if (CollectionUtils.isNotEmpty(gameChannelList)) {
			for (JuheGameChannel gameChannel : gameChannelList) {
				if (!info.getRecordId().equals(gameChannel.getRecordId())) {
					return R.failed("游戏渠道配置的渠道或游戏不准修改");
				}
			}
		}
		info = JSON.parseObject(JSON.toJSONString(juheGameChannel), JuheGameChannel.class);
		if (CollectionUtils.isNotEmpty(juheGameChannel.getAttrValueList())) {
			for (AttrValueRequest attr : juheGameChannel.getAttrValueList()) {
				JuheChannelAttr channelAttr = juheChannelAttrMapper.selectOne(new QueryWrapper<JuheChannelAttr>().eq("channel_id", channelInfo.getChannelId()).eq("attr_key", attr.getAttrKey()));
				if (null == channelAttr) {
					throw new BusinessException(1000, "该渠道的不存在KEY：" + attr.getAttrKey());
				}
				//校验华为文件类型
				if (Constant.HUAWEI_JSON_KEY.equals(attr.getAttrKey())) {
					String extension = attr.getAttrValue().substring(attr.getAttrValue().lastIndexOf('.') + 1);
					if (!Constant.JSON.equalsIgnoreCase(extension)) {
						throw new BusinessException(1000, "文件不合法,必须为" + Constant.JSON + "文件");
					}
				}
				JuheChannelAttrValue attrValue = juheChannelAttrValueMapper.selectOne(new QueryWrapper<JuheChannelAttrValue>().eq("channel_id", channelInfo.getChannelId()).eq("game_id", gameInfo.getGameId()).eq("attr_id", channelAttr.getAttrId()).eq("del_flag", Constant.DEL_NO));
				if (null == attrValue) {
					attrValue = new JuheChannelAttrValue();
					attrValue.setAttrId(channelAttr.getAttrId());
					attrValue.setAttrValue(attr.getAttrValue());
					attrValue.setChannelId(channelInfo.getChannelId());
					attrValue.setGameId(gameInfo.getGameId());
					juheChannelAttrValueMapper.insert(attrValue);
				} else {
					attrValue.setAttrValue(attr.getAttrValue());
					juheChannelAttrValueMapper.updateById(attrValue);
				}
			}
		}
		int statusNum = baseMapper.updateById(info);
		if (statusNum > 0) {
			return R.ok();
		} else {
			return R.failed("更新操作异常");
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R delGameChannelById(Long recordId) {
		JuheGameChannel info = baseMapper.selectById(recordId);
		if (null == info) {
			return R.failed("游戏渠道不存在");
		}
		info.setDelFlag(Constant.DEL_YES);
		int statusNum = baseMapper.updateById(info);
		List<JuheChannelAttrValue> list = juheChannelAttrValueMapper.selectList(new QueryWrapper<JuheChannelAttrValue>().eq("channel_id", info.getChannelId()).eq("game_id", info.getGameId()).eq("del_flag", Constant.DEL_NO));
		if (CollectionUtils.isNotEmpty(list)) {
			for (JuheChannelAttrValue attrValue : list) {
				attrValue.setDelFlag(Constant.DEL_YES);
				juheChannelAttrValueMapper.updateById(attrValue);
			}
		}
		if (statusNum > 0) {
			return R.ok();
		} else {
			return R.failed("删除操作异常");
		}
	}
}
